#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <unistd.h>
#include <pthread.h>


class Consumer
{

 

 enum{SOCKETFD_ERRNO = 1,SOCKETBIND_ERRNO = 2,RECVFROM_ERRNO = 3};

public:
    Consumer(const std::string& ip = INADDR_ANY,uint16_t port = 8080)
    :_ip(ip),_port(port),_socketfd(-1)
    {}

    void initconsumer()
    {
         _socketfd = socket(AF_INET,SOCK_DGRAM,0);
        
        if(_socketfd == - 1)
        {
            std::cout << errno << strerror(errno) << std::endl;
            exit(1);
        }
        std::cout << "socket sucess : " << _socketfd << std::endl;
        //注意了客户端不需要自己链接bind，因为客户端的ip和客户端并不重要
    }

    //别忘记了this指针，使用多线程编程，不仅可以解决打印混乱的问题，还可以实现解耦
    static void *listen(void * arvg)
    {
          int  _socketfd = *(static_cast<int*>(arvg));
          //接收客户端返回的结果
         while(1)
         {
            char Rebuffer[1024];
            struct sockaddr_in receive;
            bzero(&receive,sizeof(receive));
            socklen_t len = sizeof(receive);
            int n = recvfrom(_socketfd,Rebuffer,sizeof Rebuffer - 1 ,0 , (struct sockaddr*)&receive,&len);
            if(n > 0);
            {
                Rebuffer[n] = 0;
                std::cout << Rebuffer << std::endl;
            }
         }
    }

    void start()
    {
        pthread_create(&read,nullptr,listen,(void *)&_socketfd);

        struct sockaddr_in address;
        bzero(&address,sizeof address);
        //获取服务端信息
        address.sin_addr.s_addr = inet_addr(_ip.c_str());
        address.sin_family = AF_INET;
        address.sin_port = htons(_port);

        char buffer[1024];
        while(1)
        {
            usleep(5000);
            std::cout << "Pelase,cin#";
            //这要输入遇到空格就停止了，我们换fgets来输入
            //std::cin >> buffer;
          
            //输入到标准输入流
            fgets(buffer,sizeof buffer,stdin);
 
            buffer[strlen(buffer)-1] = 0;

            sendto(_socketfd,buffer,sizeof buffer,0,(sockaddr*)&address,sizeof address);
           
        }
    }

private:
    std::string _ip;
    uint16_t _port;
    int _socketfd;
    pthread_t read;
};
